using System;
using System.Data;
using System.Collections.Generic;
using System.Text;

using AIFSContentManagementSystem;
using AIFSContentManagementSystem.Criteria;

namespace AIFSCMSDataAccessLayer.ProxyModels
{
    public class CriterionProxy : Criterion
    {
        IRepositoryMap repositoryMap;

        public IRepositoryMap RepositoryMap
        {
            get { return repositoryMap; }
            set { repositoryMap = value; }
        }

        public CriterionProxy()
        {
        }

        #region Lazy loading

        bool areCriteriaExpressionLoaded;
        object criteriaExpressionLoadLock = new object();

        /// <summary>
        /// Used by internal objects to get the strongly typed criterion expression list
        /// </summary>
        public override List<Expression> CriteriaExpression
        {
            get
            {
                if (!areCriteriaExpressionLoaded)
                {
                    lock (criteriaExpressionLoadLock)
                    {
                        if (!areCriteriaExpressionLoaded)
                        {
                            base.CriteriaExpression = new List<Expression>();
                            ICriteriaRepository criteriaRepository = this.RepositoryMap.Get<ICriteriaRepository>();
                            List<ExpressionElement> elements = criteriaRepository.GetExpressionElementForCriterion(this.CriteriaId);
                            foreach (ExpressionElement element in elements)
                            {
                                Expression expression = Expression.CreateInstance(element.DataType);
                                expression.ExpressionElement = element;
                                base.CriteriaExpression.Add(expression);
                            }

                            areCriteriaExpressionLoaded = true;
                        }
                    }
                }

                return base.CriteriaExpression;
            }
            set
            {
                base.CriteriaExpression = value;
            }
        }

        #endregion
    }
}

